<template>
  <div class="login-container">
    <div class="title-container">
      <!-- <img class="img" src="../../assets/imgs/title.png" /> -->
      <h3 class="title">住友佳木管理系统</h3>
      <el-form
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        autocomplete="on"
        label-position="left"
      >
        <el-form-item prop="username">
          <span class="svg-container">
            <svg-icon icon-class="user" />
          </span>
          <el-input
            ref="username"
            v-model="loginForm.username"
            placeholder="请输入用户名"
            name="username"
            type="text"
            tabindex="1"
            autocomplete="on"
          />
        </el-form-item>

        <el-tooltip
          v-model="capsTooltip"
          content="Caps lock is On"
          placement="right"
          manual
        >
          <el-form-item prop="password">
            <span class="svg-container">
              <svg-icon icon-class="password" />
            </span>
            <el-input
              size="medium"
              :key="passwordType"
              ref="password"
              v-model="loginForm.password"
              :type="passwordType"
              placeholder="请输入密码"
              name="password"
              tabindex="2"
              autocomplete="on"
              @keyup.native="checkCapslock"
              @blur="capsTooltip = false"
              @keyup.enter.native="handleLogin"
            />
            <span class="show-pwd" @click="showPwd">
              <svg-icon
                :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
              />
            </span>
          </el-form-item>
        </el-tooltip>
        <el-button
          :loading="loading"
          style="
            width: 25vw;
            height: 3vw;
            background: linear-gradient(#6288b7 0%, #394c65 100%);
            color: #fff;
            font-size: 1.5vw;
            letter-spacing: 10px;
          "
          @click.native.prevent="handleLogin"
        >
          {{ loadingText }}
        </el-button>
      </el-form>
    </div>
  </div>
</template>

<script>
import { validUsername } from "@/utils/validate";
import { MessageBox, Message } from "element-ui";
import { login } from "@/api/login";
import { setStorage, getStorage, hasStorage } from "@/utils/storage";

export default {
  name: "Login",

  data() {
    const validateUsername = (rule, value, callback) => {
      if (value.trim() == "") {
        callback(new Error("请输入账号"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.trim() == "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      loadingText: "登录",
      loginForm: {
        username: "admin",
        password: "123456",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
      },
      passwordType: "password",
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
    },
    "loginForm.username": function (curVal, oldVal) {
      console.log(curVal);
      if (!curVal) {
        this.loginForm.username = "";
        return false;
      }
      this.loginForm.username = curVal.replace(/[\W]/g, "");
    },
  },
  created() {
    // if (this.$route.query.token) {
    //   this.$message({
    //     message: "token失效 请重新登陆",
    //     type: "error",
    //   });
    // }
  },
  mounted() {
    console.log(process.env.VUE_APP_BASE_API);
    if (this.loginForm.username === "") {
      this.$refs.username.focus();
    } else if (this.loginForm.password === "") {
      this.$refs.password.focus();
    }
  },
  destroyed() {},
  methods: {
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    handleLogin() {
      if (this.loginForm.username.trim() == "") {
        this.$message({
          message: "账号不能为空！",
          type: "error",
        });
        return;
      }
      if (this.loginForm.password.trim() == "") {
        this.$message({
          message: "密码不能为空！",
          type: "error",
        });
        return;
      }
      if (this.loginForm.username.trim() != "admin" || this.loginForm.password.trim() != "123456") {
      this.$message({
        message: "账号密码错误！",
        type: "error",
      });
      return;
      }
      this.loading = true;
      this.loadingText = "正在登录...";
      if (this.loginForm.username && this.loginForm.password) {
        this.goToHome()
        // this.goToLogIn();
      }
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
    goToLogIn() {
      login({
        name: this.loginForm.username,
        password: this.loginForm.password,
      })
        .then((res) => {
          if (res.success) {
            this.loading = false;
            this.$store.dispatch("user/getMenu");
            localStorage.setItem("token", res.data.token);
            setStorage("systemName", res.data.systemName);
            setStorage("userInfo", JSON.stringify(res.data.userInfo));
            this.$message({
              message: "登录成功",
              type: "success",
            });
            const redirect = this.$route.query.redirect || "/homePage";
            setTimeout(() => {
              this.$router.push({ path: redirect });
            }, 500);
          } else {
            this.loading = false;
            this.loadingText = "重新登录";
            this.$message({
              message: res.msg,
              type: "error",
            });
          }
        })
        .catch((err) => {
          this.loadingText = "重新登录";
          this.loading = false;
        });
    },
    goToHome() {
      /**
     * {
        "success": true,
        "msg": "登录成功",
        "code": "200",
        "data": {
          "userInfo": {
            "id": 1,
            "userName": "系统管理员",
            "loginName": "admin",
            "password": "1be100c24ae44aaad35c5f488c749b38",
            "phone": null,
            "oldPassword": null,
            "roleIdList": null,
            "shopCodes": null
          },
          "systemName": "智慧社区",
          "token": "uKjgzKqe9EDJrPthMhx71g=="
        }
      }
      */
      let userInfo = {
        id: 1,
        userName: "系统管理员",
        loginName: "admin",
        password: "1be100c24ae44aaad35c5f488c749b38",
        phone: null,
        oldPassword: null,
        roleIdList: null,
        shopCodes: null,
      };
      this.loading = false;
      this.$store.dispatch("user/getMenu");
      localStorage.setItem("token", "uKjgzKqe9EDJrPthMhx71g");
      setStorage("systemName", "智慧社区");
      setStorage("userInfo", JSON.stringify(userInfo));
      this.$message({
        message: "登录成功",
        type: "success",
      });
      const redirect = this.$route.query.redirect || "/homePage";
      setTimeout(() => {
        this.$router.push({ path: redirect });
      }, 500);
    },
  },
  mounted() {},
};
</script>

<style lang="scss">
$bg: #fff;
$light_gray: #000;
$cursor: #000;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: #000;
  }
}

.login-container {
  background: url("../../assets/imgs/bg.jpg") no-repeat center;
  background-size: 100% 100%;
  .el-input {
    display: inline-block;
    // height: 47px;
    width: 85%;
    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      // height: 47px;
      caret-color: #000;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: #000 !important;
      }
    }
    .el-form-item {
      border: 1px solid rgba(255, 255, 255, 0.1);
      background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #454545;
    }
  }
  .el-form-item--medium .el-form-item__content {
    line-height: 40px !important;
  }
  input {
    filter: none !important;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  el-input input {
    color: #000;
  }
  .login-form {
    position: relative;
    width: 25vw;
    max-width: 100%;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;
    margin-left: 40vw;
    text-align: center;
    padding-top: 15vh;
    .title {
      height: 41px;
      opacity: 1;
      font-size: 44px;
      font-family: PingFang SC Medium, PingFang SC Medium-Medium;
      font-weight: 500;
      text-align: center;
      color: #4d657b;
      line-height: 19px;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
  .img {
    width: 172px;
    height: 92px;
  }
  .el-form-item {
    width: 25vw;
  }
}
.login-container .el-form-item {
  display: inline-block;
  background-color: #fff;
  border: 1px solid #ccc;
}
.el-form-item--medium .el-form-item__content {
  line-height: 0px !important;
}
</style>
